﻿using System;
using System.Collections.Generic;
using System.Net.Mail;

namespace Utilites
{
    /// <summary>
    /// Класс для отправки Email
    /// </summary>
    public static class Mail
    {
        /// <summary>
        /// Функция отправки письма
        /// </summary>
        /// <param name="sendTo"></param>
        /// <param name="sendFrom"></param>
        /// <param name="subject"></param>
        /// <param name="body"></param>
        /// <param name="attachmentPath"></param>
        /// <param name="serverAddress"></param>
        /// <param name="serverPort"></param>
        /// <returns>null - если все ОК или строку ошибки</returns>
        public static string SendMail(string sendTo, string sendFrom, string subject, string body, string attachmentPath, string serverAddress, int serverPort)
        {
            //проверка параметров
            if (string.IsNullOrEmpty(sendTo)) return "sendTo is empty";
            if (string.IsNullOrEmpty(body)) return "body is empty";
            if (string.IsNullOrEmpty(sendFrom)) return "sendFrom is empty";
            if (string.IsNullOrEmpty(serverAddress)) return "serverAddress is empty";
            if (serverPort <= 0) return "error server port";

            try
            {
                MailMessage message = new MailMessage(sendFrom, sendTo);

                //заполнение обязательных параметров
                message.Body = body;
                message.Sender = new MailAddress(sendFrom);

                //заполнение необязательных параметров
                if (!string.IsNullOrEmpty(subject)) message.Subject = subject;
                if (!string.IsNullOrEmpty(attachmentPath))
                {
                    var attachment = new Attachment(attachmentPath);
                    message.Attachments.Add(attachment);
                }
                
                SmtpClient client = new SmtpClient(serverAddress, serverPort);
                
                try
                {
                    client.Send(message);
                }
                catch (SmtpFailedRecipientsException ex)
                {
                    for (int i = 0; i < ex.InnerExceptions.Length; i++)
                    {
                        SmtpStatusCode status = ex.InnerExceptions[i].StatusCode;
                        if (status == SmtpStatusCode.MailboxBusy ||
                           status == SmtpStatusCode.MailboxUnavailable)
                        {

                            System.Threading.Thread.Sleep(5000);
                            client.Send(message);
                        }
                        else
                        {
                            // Console.WriteLine("Failed to deliver message to {0}",
                            //  ex.InnerExceptions[i].FailedRecipient); 
                        }
                    }
                }
                catch (Exception ex)
                {
                    return "Ошибка! Исключение отправки письма:" + ex.Message;
                }
            }
            catch (Exception ex)
            {
                return "Ошибка! Общее исключение:" + ex.Message;
            }

            return null;
        }

        //-------------------------------------

        public static void sendMail(string SendTo, string SendFrom, string Subject, string Body, Attachment attachment)
        {
            if (SendTo != "")
            {
                MailMessage mess = new MailMessage(SendFrom, SendTo);
                mess.Body = Body;
                mess.Subject = Subject;
                mess.IsBodyHtml = true;
                if (attachment != null) mess.Attachments.Add(attachment);
              //  mess.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;
                SmtpClient client = new SmtpClient("10.245.14.3", 25);
                mess.Sender = new MailAddress(SendFrom);

                try
                {
                    client.Send(mess);
                }
                catch (SmtpFailedRecipientsException ex)
                {
                    for (int i = 0; i < ex.InnerExceptions.Length; i++)
                    {
                        SmtpStatusCode status = ex.InnerExceptions[i].StatusCode;
                        if (status == SmtpStatusCode.MailboxBusy ||
                            status == SmtpStatusCode.MailboxUnavailable)
                        {

                            System.Threading.Thread.Sleep(5000);
                            client.Send(mess);
                        }
                        else
                        {
                            // Console.WriteLine("Failed to deliver message to {0}",
                            //  ex.InnerExceptions[i].FailedRecipient);
                        }
                    }
                }
                catch (Exception ex)
                {
                    // Console.WriteLine("Exception caught in RetryIfBusy(): {0}",
                    //    ex.ToString());
                }

            }
        }

        public static string sendMail(string SendTo, string SendFrom, string Subject, string Body, string  attachmentPath)
        {
            try
            {
                if (SendTo != "")
                {
                    MailMessage mess = new MailMessage(SendFrom, SendTo);
                    Attachment attachment = null;
                    mess.Body = Body;
                    mess.Subject = Subject;
                    mess.IsBodyHtml = true;
                    if (!string.IsNullOrEmpty(attachmentPath))
                    {
                        attachment = new Attachment(attachmentPath);
                    }
                    if (attachment != null) mess.Attachments.Add(attachment);
                    //  mess.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;
                    SmtpClient client = new SmtpClient("10.245.14.3", 25);
                    mess.Sender = new MailAddress(SendFrom);

                    try
                    {
                        client.Send(mess);
                    }
                    catch (SmtpFailedRecipientsException ex)
                    {
                        for (int i = 0; i < ex.InnerExceptions.Length; i++)
                        {
                            SmtpStatusCode status = ex.InnerExceptions[i].StatusCode;
                            if (status == SmtpStatusCode.MailboxBusy ||
                                status == SmtpStatusCode.MailboxUnavailable)
                            {

                                System.Threading.Thread.Sleep(5000);
                                client.Send(mess);
                            }
                            else
                            {
                                // Console.WriteLine("Failed to deliver message to {0}",
                                //  ex.InnerExceptions[i].FailedRecipient);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        return ex.Message;
                    }

                }
            }
            catch(Exception ex)
            {
                return ex.Message;
            }

            return "";
        }
        
        public static void sendMail(string SendTo, string SendFrom, string Subject, string Body)
        {
            if (SendTo != "")
            {
                try
                {
                    MailMessage mess = new MailMessage(SendFrom, SendTo);
                    mess.Body = Body;
                    mess.Subject = Subject;
                    mess.IsBodyHtml = true;

                    SmtpClient client = new SmtpClient("10.245.14.3", 25);
                    mess.Sender = new MailAddress(SendFrom);

                    try
                    {
                        client.Send(mess);
                    }
                    catch (SmtpFailedRecipientsException ex)
                    {
                        for (int i = 0; i < ex.InnerExceptions.Length; i++)
                        {
                            SmtpStatusCode status = ex.InnerExceptions[i].StatusCode;
                            if (status == SmtpStatusCode.MailboxBusy ||
                                status == SmtpStatusCode.MailboxUnavailable)
                            {

                                System.Threading.Thread.Sleep(5000);
                                client.Send(mess);
                            }

                        }
                    }
                    catch (Exception ex)
                    {
                        // Console.WriteLine("Exception caught in RetryIfBusy(): {0}",
                        //    ex.ToString());
                    }
                }

                catch
                {
                }
            }
        }

        public static void sendMail(string SendTo, string SendFrom, string Subject, string Body, List<Attachment> attachments)
        {
            if (SendTo != "")
            {
                MailMessage mess = new MailMessage(SendFrom, SendTo);
                mess.Body = Body;
                mess.IsBodyHtml = true;
                mess.Subject = Subject;
                if (attachments != null)
                    foreach (Attachment attachment in attachments)
                    {
                        mess.Attachments.Add(attachment);
                    }
                SmtpClient client = new SmtpClient("10.245.14.3", 25);
                mess.Sender = new MailAddress(SendFrom);

                try
                {
                    client.Send(mess);
                }
                catch (SmtpFailedRecipientsException ex)
                {
                    for (int i = 0; i < ex.InnerExceptions.Length; i++)
                    {
                        SmtpStatusCode status = ex.InnerExceptions[i].StatusCode;
                        if (status == SmtpStatusCode.MailboxBusy ||
                            status == SmtpStatusCode.MailboxUnavailable)
                        {

                            System.Threading.Thread.Sleep(5000);
                            client.Send(mess);
                        }
                        else
                        {
                            // Console.WriteLine("Failed to deliver message to {0}",
                            //  ex.InnerExceptions[i].FailedRecipient);
                        }
                    }
                }
                catch (Exception ex)
                {
                    // Console.WriteLine("Exception caught in RetryIfBusy(): {0}",
                    //    ex.ToString());
                }

            }
        }
        
        public static void sendMail(List<MailAddress> SendTo, MailAddress SendFrom, List<MailAddress> SendCC, string Subject, string Body, List<Attachment> attachments)
        {
            
                MailMessage mess = new MailMessage();
                mess.Body = Body;
                
                mess.Subject = Subject;
            foreach(MailAddress mailAddress in SendTo)
            {
                mess.To.Add(mailAddress);
            }
            foreach (MailAddress mailAddress in SendCC)
            {
                mess.CC.Add(mailAddress);
            }
                if (attachments != null)
                    foreach (Attachment attachment in attachments)
                    {
                        mess.Attachments.Add(attachment);
                    }
                SmtpClient client = new SmtpClient("10.245.14.3", 25);
            mess.Sender = SendFrom;

                try
                {
                    client.Send(mess);
                }
                catch (SmtpFailedRecipientsException ex)
                {
                    for (int i = 0; i < ex.InnerExceptions.Length; i++)
                    {
                        SmtpStatusCode status = ex.InnerExceptions[i].StatusCode;
                        if (status == SmtpStatusCode.MailboxBusy ||
                            status == SmtpStatusCode.MailboxUnavailable)
                        {

                            System.Threading.Thread.Sleep(5000);
                            client.Send(mess);
                        }
                        else
                        {
                            // Console.WriteLine("Failed to deliver message to {0}",
                            //  ex.InnerExceptions[i].FailedRecipient);
                        }
                    }
                }
                catch (Exception ex)
                {
                    // Console.WriteLine("Exception caught in RetryIfBusy(): {0}",
                    //    ex.ToString());
                }

            
        }

        // Private Sub sendMailViaSMTP(ByVal SendTo As String, ByVal SendFrom As String, ByVal Subject As String, ByVal Body As String)
        //    Dim mess As New MailMessage("maksim", SendTo)
        //    mess.From = New MailAddress("sukonah@ya.ru")
        //    mess.Body = Body
        //    mess.Subject = Subject
        //    Dim client As New SmtpClient("10.245.14.3", 25)
        //    client.Send(mess)
        //End Sub
    }
}
